import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { customers } from '@/lib/schema';
import { eq } from 'drizzle-orm';

export async function GET() {
  try {
    const allCustomers = await db.select().from(customers);
    return NextResponse.json(allCustomers);
  } catch (error) {
    console.error('获取客户列表失败:', error);
    return NextResponse.json(
      { error: '获取客户列表失败' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    
    const [newCustomer] = await db
      .insert(customers)
      .values({
        name: body.name,
        email: body.email,
        phone: body.phone,
        phone2: body.phone2,
        phone2Purpose: body.phone2Purpose,
        wechat: body.wechat,
        wechatPurpose: body.wechatPurpose,
        qq: body.qq,
        qqPurpose: body.qqPurpose,
        whatsapp: body.whatsapp,
        whatsappPurpose: body.whatsappPurpose,
        telegram: body.telegram,
        telegramPurpose: body.telegramPurpose,
        address: body.address,
      })
      .returning();

    return NextResponse.json(newCustomer, { status: 201 });
  } catch (error: any) {
    console.error('创建客户失败:', error);
    
    if (error.message?.includes('UNIQUE constraint failed')) {
      return NextResponse.json(
        { error: '邮箱已存在，请使用其他邮箱地址' },
        { status: 400 }
      );
    }
    
    return NextResponse.json(
      { error: '创建客户失败: ' + (error.message || '数据库错误') },
      { status: 500 }
    );
  }
}